import { _decorator, Component, instantiate, UITransform ,Node, Canvas, Layers, Size, ResolutionPolicy, view,screen, js, Constructor, Prefab, assertID, assetManager} from 'cc';
import { ResManager } from '../res/ResManager';
import { EViewLayer } from './EViewLayer';
import { Match3UI } from '../../../GamePlay/modules/Match3/Match3UI';
import { BL } from '../res/ResConst';
import { PrefabCfg } from '../../../auto/PrefabCfg';
import { ResLoader } from '../res/ResLoader';
const { ccclass, property } = _decorator;



/** 
 * 画布的标准化尺寸，就是之前说的
 * iPad 设备中的画布尺寸 = 1001 x 1334 (其中 1001 ≈ 1668/1.6672)
 * iPhone16设备中的画布尺寸 = 750 x1626（其中 1626 = 2556/1.572）
 */
export const G_VIEW_SIZE = new Size(0, 0);
function adapterScreen() {
    let resolutionPolicy: ResolutionPolicy = view.getResolutionPolicy();
    let designSize = view.getDesignResolutionSize();
    let frameSize = screen.windowSize;
    let frameW = frameSize.width;
    let frameH = frameSize.height;
    /** 是否是屏幕更宽 */
    const isScreenWidthLarger = (frameW / frameH) > (designSize.width / designSize.height);
    let targetResolutionPolicy = isScreenWidthLarger ? ResolutionPolicy.FIXED_HEIGHT : ResolutionPolicy.FIXED_WIDTH;
    
    if(targetResolutionPolicy !== resolutionPolicy.getContentStrategy().strategy){
        view.setDesignResolutionSize(designSize.width, designSize.height, targetResolutionPolicy);
        view.emit("canvas-resize")
    }

    if(isScreenWidthLarger){
        G_VIEW_SIZE.width = Math.ceil(designSize.height * frameSize.width / frameSize.height);
        G_VIEW_SIZE.height = designSize.height

    }else{
        G_VIEW_SIZE.width = designSize.width;
        G_VIEW_SIZE.height = Math.ceil(designSize.width * frameSize.height / frameSize.width);
    }

    console.log(`屏幕${isScreenWidthLarger ? "更宽, 高度适配" : "更高, 宽度适配"} 设计分辨率比例下的屏幕尺寸: ${G_VIEW_SIZE.width}x${G_VIEW_SIZE.height}`);

    return isScreenWidthLarger;
    
}

const g_Key2BUrl = new Map<string, IBundleUrl>();
export function registerBUrlByCfg(cfg: {
    [uiClassName: string]: IBundleUrl
}) {
    for (let uiClassName in cfg) {
        g_Key2BUrl.set(uiClassName, cfg[uiClassName])
    }
}


const g_UICls2BUrl = new Map<any, IBundleUrl>();
/** 注册接口 */
export function setUIClassBUrl(uiClass: any, bUrl: IBundleUrl) {
    g_UICls2BUrl.set(uiClass, bUrl);
}
/** 获取接口 */
export function getUIClassBUrl(uiClass: any): IBundleUrl {

    if(g_UICls2BUrl.has(uiClass)){
        return g_UICls2BUrl.get(uiClass);
    }

    //如果没有从配置表中拿
    let uiClassName = js.getClassName(uiClass);
    let bUrl = g_Key2BUrl.get(uiClassName)

    if(!bUrl){
        //没有找到类名对应的预制体
        debugger;
        console.error("没有找到类名对应的预制体uiClassName",uiClassName)
        return null;
    }
    g_UICls2BUrl.set(uiClass,bUrl)

    return bUrl
}



class MyLayer {
    public readonly node: Node;
    constructor(
        public readonly layer: EViewLayer,
        public readonly canvas: Canvas,
        name: string,
    ) {
        const node = this.node = new Node(name);
        node.layer = Layers.Enum.UI_2D;
        node.addComponent(UITransform);
        canvas.node.addChild(node);
    }
}


export class UIManager{

    // private static _instance: UIManager = null!;

    // static getInstance(){
    //     if (this._instance === null) {
    //         this._instance = new UIManager();
    //     }
    //     return this._instance;
    // }

    // private constructor(){

    // }

    // open(uiClass: any) {
    //     const bUrl = getUIClassBUrl(uiClass);
    //     // ResManager.getInstance().loadPrefabByBUrl("Match3BN", "Match3UI", prefab => {
    //     gtr.res.loadPrefabByBUrl(bUrl, prefab => {
    //         let match3Node = instantiate(prefab);
    //         // this.node.addChild(match3Node);
    //         this.m_Layers[EViewLayer.UI].node.addChild(match3Node);
    //         match3Node.getComponent(UITransform).setContentSize(G_VIEW_SIZE.clone());
    //     });
    // }


    async open<UI extends Component>(uiClass: Constructor<UI> & {readonly viewLayer?:EViewLayer } ): Promise<UI> {

        const viewLayer:EViewLayer = typeof(uiClass.viewLayer) === 'number' ? uiClass.viewLayer : EViewLayer.UI;
        const resLoader = new ResLoader();
        resLoader.addUI(uiClass);
        await resLoader.load();
        let ui = this.instantiate(uiClass);
        this.m_Layers[viewLayer].node.addChild(ui.node);
        ui.getComponent(UITransform).setContentSize(G_VIEW_SIZE.clone());
        resLoader.autoRelease(ui);
        return ui;
    }

    private m_Canvas:Canvas = null;
    private m_Layers: MyLayer[] = []

    init(canvas: Canvas) {
        this.m_Canvas = canvas;
        adapterScreen()
        for (let layer = EViewLayer.Scene, maxLayer = EViewLayer.Toast; layer <= maxLayer; ++layer) {
            this.m_Layers.push(new MyLayer(layer, canvas, EViewLayer[layer]));
        }
    }

    instantiate<UE extends Component>(ueClass:Constructor<UE>):UE{

        let bUrl = getUIClassBUrl(ueClass);
        let bundle = assetManager.getBundle(bUrl.b);
        let prefab:Prefab = bundle.get(bUrl.l,Prefab);
        let node:Node = instantiate(prefab);

        return (node.getComponent(ueClass as any) || node.addComponent(ueClass as any));
    }

}
